<?php
namespace lib;

// use \GatewayWorker\Lib\DbConnection;
// use \GatewayWorker\Lib\Gateway;
use Workerman\Http\Client as HttpClient;
/**
 * 
 */
class Tools 
{
    /**
	 * 获取config信息
	 * @return  array 
	 */
	public function getConfig($p = false)
	{
	   global $config;
       if($config && !$p){
           return $config;
       }else{
           $config = require __DIR__ . '/config.php';
           return $config;
       }
       return false;
	}
	
	/**
	 * 日志记录.
	 * @param $msg String 消息名称
	 * @param $content array 具体内容
	 * @param $flag bool 是否记录
	 * @return  array 
	 */
	public function debug($msg,$content = [],$flag = true)
	{
	    $config = $this->getConfig();
        $log = new \core\Log($config['log']);
        $log->debug($msg,$content,$flag);
	}
	
	/**
	 * 计算数据流量的大小
	 * @return  array 
	 */
	public function calculateflow($data)
	{
	   return strlen($data) * 1.2;
	}
	
	/**
	 * http 异步请求
	 */
	public function http($url,$data=[],$method='POST',$headers=[])
	{
	    $http = new HttpClient();
	    if(!$headers){
	        $headers['Content-Type'] = 'application/json';
	    }
	    $http->request($url, [
            'method'  => $method,
            'version' => '1.1',
            'headers' => $headers,
            'data'    => $data,
            'success' => function ($response) {
                $code = $response->getStatusCode();
                if($code != 200){
                    $this->debug('http 请求错误'.$code.'_'.$url.$response->getBody());
                }
            },
            'error'   => function ($exception) {
                $this->debug('http 请求异常'.$url.$exception->getMessage());
            }
        ]);
	}
}
